package cn.edu.abtu.exceptionhandler;

import cn.edu.abtu.vo.ResponseData;
import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//全局异常处理
@ControllerAdvice(annotations = {RestController.class, Controller.class}) //拦截带有RestController和Controller接口的
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    // 异常处理方法,同意拦截MySQLIntegrityConstraintViolationException异常,进行统一处理
    @ExceptionHandler(MySQLIntegrityConstraintViolationException.class)
    public ResponseData exceptionHandler(MySQLIntegrityConstraintViolationException exception){
        log.error(exception.getLocalizedMessage());
        if (exception.getMessage().contains("Duplicate entry")){
            //Duplicate entry '20191446' for key 'idx_username' 按照空格截取字符串,共截取出六个字符串
            String[] split = exception.getMessage().split(" ");
            String msg = split[2] + "用户名已存在,请重试";
            return ResponseData.fail(msg,null);
        }
        return ResponseData.fail("未知错误",null);
    }

    // 异常处理方法,同意拦截ArithmeticException异常,进行统一处理
    @ExceptionHandler(ArithmeticException.class)
    public ResponseData exceptionHandler(ArithmeticException exception){
        log.error(exception.getLocalizedMessage());
        if (exception.getMessage().contains("by zero")){
            //Duplicate entry '20191446' for key 'idx_username' 按照空格截取字符串,共截取出六个字符串
            String msg = "0不能作为除数";
            log.error(msg+" ");
            return ResponseData.fail(msg,"傻逼");
        }
        return ResponseData.fail("未知错误",null);
    }

    @ExceptionHandler(GuliException.class)
    public ResponseData exceptionHandler(GuliException e){
        log.error(e.getMsg());
        return ResponseData.fail(e.getCode(),e.getMsg(),null);
    }
}
